#!/usr/bin/evn python
# examples/chat.py

try:
    import httpmessage
except ImportError:
    import sys
    from os.path import dirname, abspath, join
    sys.path.append(abspath(join(dirname(__file__), '..')))

from httpmessage import HttpMessage, RequestMessage
import httpmessage.exc as exc
import socket, select, sys

class TextChatRequest(RequestMessage):
    def __init__(self, text):
        super(TextChatRequest,self).__init__()
        self.method = 'POST'
        self.write(text)
        self.content_type = 'text/plain'
        self.content_length = self.tell()
        self.seek(0)

if __name__ == '__main__':
    netloc = ('', 7777)
    try:
        servsock = socket.socket()
        servsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        servsock.bind(netloc)
        servsock.listen(5)
        sock, _ = servsock.accept()
    except socket.error:
        sock = socket.socket()
        sock.connect(netloc)
    
    try:
        while True:
            r_ok, _, _ = select.select([sys.stdin, sock], [], [])
            for fd in r_ok:
                if fd == sys.stdin:
                    text = fd.readline().strip()
                    if text:
                        tcr = TextChatRequest(text)
                        sock.send(str(tcr))
                elif fd == sock:
                    msg = HttpMessage(socket=sock)
                    print msg.read()
    except (KeyboardInterrupt, exc.HttpMessageException):
        pass
    finally:
        print '\nexiting...'

